package org.FaPe3D.core.viewports
{
	import br.com.stimuli.loading.BulkLoader;
	import br.com.stimuli.loading.BulkProgressEvent;
	
	import flash.events.Event;
	
	import org.FaPe3D.Adapter;
	import org.FaPe3D.core.events.EventManager;
	
	public class ExternalAppendObjects extends EventManager
	{
		private var _id:String;
		private var _xml:XML;
		private var _bulkLoader:BulkLoader;
		private static var _EVENTS:String = 'events';
		private static var _PROPERTY:String = 'propertys';
		private static var _MATERIALS:String = 'materials';
		
		public function ExternalAppendObjects(id:String, xml:XML)
		{
			_id = id;
			_xml = xml;
			
			// create new bulkloader instance 
			_bulkLoader = new BulkLoader('FAPE3D_' + 'externalAppendObjects');
			// add Files
			_bulkLoader.add(Adapter.getAdapter(_id).settings.setting['path.appends'].replace('{0}', _EVENTS), { type:"xml", id: _EVENTS });
			_bulkLoader.add(Adapter.getAdapter(_id).settings.setting['path.appends'].replace('{0}', _MATERIALS), { type:"xml", id: _MATERIALS });
			_bulkLoader.add(Adapter.getAdapter(_id).settings.setting['path.appends'].replace('{0}', _PROPERTY), { type:"xml", id: _PROPERTY });
			
			// start downloading
			_bulkLoader.start();
			
			// setup bulkloader events
			_bulkLoader.addEventListener(BulkProgressEvent.COMPLETE, parse);
			_bulkLoader.addEventListener(BulkLoader.PROGRESS, loadingProgress);
			_bulkLoader.addEventListener(BulkLoader.ERROR, loadingError)
		}
		
		private function parse(e:BulkProgressEvent)
		{
			
			var i1:Number=0;
			while(i1 < _xml..materials.@id.length())
			{
				_xml..materials.@id[i1].parent().prependChild( _bulkLoader.getXML(_MATERIALS)..materials.(@id == _xml..materials.@id[i1]+'').children() );
				i1++;
			}
		
			var i2:Number=0;
			while(i2 < _xml..events.@id.length())
			{
				_xml..events.@id[i2].parent().prependChild( _bulkLoader.getXML(_EVENTS)..events.(@id == _xml..events.@id[i2]+'').children() );
				i2++;
			}
			
			var i3:Number=0;
			while(i3 < _xml..property.@id.length())
			{
				_xml..property.@id[i3].parent().prependChild( _bulkLoader.getXML(_PROPERTY)..property.(@id == _xml..property.@id[i3]+'').children() );
				i3++;
			}
			
			dispatchEvent(new Event( Event.COMPLETE ));
			_bulkLoader.removeAll();
		}
		
		public function get xml():XML
		{
			return _xml;
		}
		
		private function loadingProgress(e:*):void
		{
//			trace('loading progress', e.bytesLoaded , '/', e.bytesTotal);
		}
		
		private function loadingError(e:*):void
		{
			trace('error in loading xml file. (externalAppendObjects)' , e);
		}
		
	}
}